<template>
  <div class="movie-manage">
    <div class="page-header">
      <h2>影片管理</h2>
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>
        新增影片
      </el-button>
    </div>
    
    <el-card>
      <template #header>
        <div class="table-header">
          <span>影片列表</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索影片标题"
              style="width: 200px; margin-right: 10px;"
              clearable
            />
            <el-select v-model="searchCategory" placeholder="选择分类" style="width: 150px; margin-right: 10px;">
              <el-option label="全部" value="" />
              <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
            </el-select>
            <el-button @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="movieList" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="title" label="标题" min-width="200" />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="year" label="年份" width="80" />
        <el-table-column prop="actors" label="演员" width="150">
          <template #default="scope">
            <span>{{ scope.row.actors?.map(actor => actor.name).join(', ') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="quality" label="清晰度" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.quality" :type="getQualityType(scope.row.quality)">{{ scope.row.quality }}</el-tag>
            <span v-else style="color: #999;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            <span v-if="scope.row.createdAt">{{ scope.row.createdAt }}</span>
            <span v-else style="color: #999;">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="primary" @click="handleSource(scope.row)">片源</el-button>
            <el-button size="small" type="warning" @click="handleSubtitle(scope.row)">字幕</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 影片编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form ref="movieFormRef" :model="movieForm" :rules="movieRules" label-width="100px">
        <el-form-item label="影片标题" prop="title">
          <el-input v-model="movieForm.title" placeholder="请输入影片标题" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="movieForm.categoryId" placeholder="请选择分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="演员" prop="actors">
          <el-select 
            v-model="movieForm.actorIds" 
            multiple 
            filterable 
            remote
            reserve-keyword
            :remote-method="searchActors"
            :loading="actorLoading"
            placeholder="请输入演员姓名搜索"
          >
            <el-option 
              v-for="actor in actorOptions" 
              :key="actor.id" 
              :label="actor.name" 
              :value="actor.id" 
            />
          </el-select>
          <div style="font-size: 12px; color: #666; margin-top: 5px;">
            支持搜索现有演员，系统会自动创建新演员
          </div>
        </el-form-item>
        <el-form-item label="上映年份" prop="year">
          <el-input-number 
            v-model="movieForm.year" 
            :min="1900" 
            :max="2030" 
            placeholder="请输入上映年份" 
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="清晰度" prop="quality">
          <el-select v-model="movieForm.quality" placeholder="请选择清晰度">
            <el-option label="标清" value="SD" />
            <el-option label="高清" value="HD" />
            <el-option label="超清" value="FHD" />
            <el-option label="4K" value="4K" />
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="movieForm.description" type="textarea" :rows="4" placeholder="请输入影片简介" />
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
          <el-upload
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            @change="handleCoverChange"
          >
            <el-button type="primary">选择图片</el-button>
            <template #tip>
              <div class="el-upload__tip">建议尺寸 300x450px，支持 JPG/PNG 格式</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="movieForm.status" placeholder="请选择状态">
            <el-option label="待审核" value="review" />
            <el-option label="已发布" value="published" />
            <el-option label="已下架" value="offline" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { movieService } from '../../services/movieService'
import { categoryService } from '../../services/categoryService'
import { actorService } from '../../services/actorService'

const loading = ref(false)
const searchKeyword = ref('')
const searchCategory = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('新增影片')
const movieFormRef = ref()

const categories = ref([])
const actorOptions = ref([])
const actorLoading = ref(false)
const movieList = ref([])

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const movieForm = reactive({
  id: null,
  title: '',
  categoryId: '',
  actorIds: [], // 存储演员ID数组
  actors: [],   // 存储完整的演员对象数组
  year: new Date().getFullYear(), // 默认当前年份
  quality: 'HD',
  description: '',
  cover: '',
  status: 'published' // 默认状态为已发布
})

const movieRules = {
  title: [{ required: true, message: '请输入影片标题', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
  year: [
    { required: true, message: '请输入上映年份', trigger: 'blur' },
    { type: 'number', min: 1900, max: 2030, message: '年份必须在1900-2030之间', trigger: 'blur' }
  ]
}

const getQualityType = (quality) => {
  const qualityMap = {
    'SD': 'info',
    'HD': 'primary',
    'FHD': 'warning',
    '4K': 'danger'
  }
  return qualityMap[quality] || 'info'
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  
  // 如果是字符串格式，直接返回
  if (typeof dateTime === 'string') {
    return dateTime
  }
  
  // 如果是Date对象，格式化
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}



// 加载影片列表
const loadMovies = async () => {
  loading.value = true
  try {
    const response = await movieService.getMovies({
      page: pagination.current - 1,
      size: pagination.size,
      search: searchKeyword.value,
      categoryId: searchCategory.value
    })
    movieList.value = response.data.content || []
    pagination.total = response.data.totalElements || 0
    
  
  } catch (error) {
    console.error('加载影片列表失败:', error)
    ElMessage.error('加载影片列表失败')
  } finally {
    loading.value = false
  }
}

// 加载演员列表
const loadActors = async () => {
  try {
    const response = await actorService.getActors({
      page: 0,
      size: 100
    })
    actorOptions.value = response.data.content || []
  } catch (error) {
    console.error('加载演员列表失败:', error)
  
  }
}


// 加载分类列表
const loadCategories = async () => {
  try {
    const response = await categoryService.getAllCategories()
    categories.value = response.data || []
  } catch (error) {
    console.error('加载分类列表失败:', error)
    ElMessage.error('加载分类列表失败')
  }
}

// 演员搜索功能
const searchActors = async (query) => {
  if (query) {
    actorLoading.value = true
    try {
      const response = await actorService.searchActors(query)
      // 后端返回的是 List<ActorDTO>，直接使用 response.data
      actorOptions.value = response.data || []
    } catch (error) {
      console.error('搜索演员失败:', error)
      // 如果搜索失败，使用本地过滤
      actorOptions.value = actorOptions.value.filter(actor => 
        actor.name.toLowerCase().includes(query.toLowerCase())
      )
    } finally {
      actorLoading.value = false
    }
  } else {
    // 如果查询为空，重新加载所有演员
    loadActors()
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadMovies()
}

const handleReset = () => {
  searchKeyword.value = ''
  searchCategory.value = ''
  pagination.current = 1
  loadMovies()
}

const handleCreate = () => {
  dialogTitle.value = '新增影片'
  Object.assign(movieForm, {
    id: null,
    title: '',
    categoryId: '',
    actorIds: [],
    actors: [],
    year: new Date().getFullYear(),
    quality: 'HD',
    description: '',
    cover: '',
    status: 'published'
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑影片'
  Object.assign(movieForm, { ...row })
  
  // 设置演员ID数组，用于下拉框显示
  if (row.actors && Array.isArray(row.actors)) {
    movieForm.actorIds = row.actors.map(actor => actor.id)
  } else {
    movieForm.actorIds = []
  }
  
  dialogVisible.value = true
}

const handleSource = (row) => {
  ElMessage.info(`配置片源: ${row.title}`)
}

const handleSubtitle = (row) => {
  ElMessage.info(`上传字幕: ${row.title}`)
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除影片 "${row.title}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await movieService.deleteMovie(row.id)
    ElMessage.success('删除成功')
    loadMovies()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除影片失败:', error)
      ElMessage.error('删除影片失败')
    }
  }
}

const handleCoverChange = (file) => {
  console.log('封面图选择:', file)
}

const handleDialogClose = () => {
  movieFormRef.value?.resetFields()
}

const handleSubmit = async () => {
  if (!movieFormRef.value) return
  
  try {
    const valid = await movieFormRef.value.validate()
    if (!valid) return
    
    // 根据演员ID数组获取完整的演员对象
    const selectedActors = actorOptions.value.filter(actor => 
      movieForm.actorIds.includes(actor.id)
    )
    
    // 准备提交数据 - 移除前端特有的字段，只保留后端需要的字段
    const submitData = {
      id: movieForm.id,
      title: movieForm.title,
      categoryId: movieForm.categoryId,
      actors: selectedActors,
      year: movieForm.year,
      quality: movieForm.quality,
      description: movieForm.description,
      cover: movieForm.cover,
      status: movieForm.status
    }
    
    if (movieForm.id) {
      // 编辑影片
      await movieService.updateMovie(movieForm.id, submitData)
      ElMessage.success('编辑影片成功')
    } else {
      // 新增影片
      await movieService.createMovie(submitData)
      ElMessage.success('新增影片成功')
    }
    
    dialogVisible.value = false
    loadMovies()
  } catch (error) {
    console.error('保存影片失败:', error)
    ElMessage.error('保存影片失败')
  }
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadMovies()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadMovies()
}

onMounted(() => {
  loadCategories()
  loadMovies()
  loadActors()
})
</script>

<style scoped>
.movie-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>